#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from logging.handlers import TimedRotatingFileHandler
import os, sys
import asyncio
from robyn.logger import logger

from settings.config import settings

async def create_directories():
    await asyncio.to_thread(os.makedirs, os.path.dirname(settings.LOG_ERROR_DIR), exist_ok=True)
    await asyncio.to_thread(os.makedirs, os.path.dirname(settings.LOG_INFO_DIR), exist_ok=True)

async def init_log():
    # 确保日志目录存在
    await create_directories()

     # 配置控制台日志
    console_handler = logging.StreamHandler(sys.stderr)
    console_formatter = logging.Formatter(
        "{asctime} [ThreadID:{thread}] [{levelname}] {name} {funcName}:{lineno} - {message}",
        style="{"
    )
    console_handler.setFormatter(console_formatter)
    console_handler.setLevel(logging.DEBUG)

    # 配置 error 日志
    error_handler = TimedRotatingFileHandler(
        filename=settings.LOG_ERROR_DIR,
        when="midnight",
        interval=1,
        backupCount=30,
        encoding='utf-8'
    )
    error_formatter = logging.Formatter(
        "{asctime} [ThreadID:{thread}] [{levelname}] {name} {funcName}:{lineno} - {message}",
        style="{",
    )
    error_handler.setFormatter(error_formatter)
    error_handler.setLevel(logging.ERROR)

    # 配置 info 日志
    info_handler = TimedRotatingFileHandler(
        filename=settings.LOG_INFO_DIR,
        when="midnight",
        interval=1,
        backupCount=30,
        encoding='utf-8'
    )
    info_formatter = logging.Formatter(
        "{asctime} [ThreadID:{thread}] [{levelname}] {name} {funcName}:{lineno} - {message}",
        style="{"
    )
    info_handler.setFormatter(info_formatter)
    info_handler.setLevel(logging.DEBUG)

    # 创建根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    root_logger.addHandler(console_handler)
    root_logger.addHandler(error_handler)
    root_logger.addHandler(info_handler)

    # 设置标准库 `logging` 的日志级别
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("tortoise").setLevel(logging.WARNING)
    logging.getLogger("asyncio").setLevel(logging.WARNING)
    logging.getLogger("docker").setLevel(logging.WARNING)
    logging.getLogger("multipart").setLevel(logging.WARNING)
    logging.getLogger("robyn").setLevel(logging.WARNING)